<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="listInfo"
    :columns="columns"
    row-key="modelId"
    :rowSelection="rowSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()" code="deviceMode:add"
          >新增</b-button
        >
        <b-button
          icon="delete"
          @click="onDelete()"
          :disabled="!selectedRowKeys.length"
          code="deviceMode:remove"
          >删除</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button
        icon="edit"
        type="link"
        @click="onView(record)"
        code="deviceMode:query"
        >详情</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { hasPermission } from '@/permission';
import { Modal, Space, message } from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToEnum, listToOption } from '@/utils/utils';
import { addInfo, delInfo, listInfo, updateInfo } from '@/api/device';
import { fetchDictOfType } from '@/api/dict';

const selectedRowKeys = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectedRowKeys.value,
    onChange(values) {
      selectedRowKeys.value = values;
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.useCount > 0,
    }),
  };
});
const tableRef = ref();
const sysDeviceModeEnum = ref<Record<string, any>>({});
const sysDeviceModeOption = ref<Global.Option[]>([]);
const init = () => {
  fetchDictOfType('sys_device_mode').then((res: any) => {
    sysDeviceModeEnum.value = listToEnum(res.data, 'dictValue', 'dictLabel');
    sysDeviceModeOption.value = listToOption(
      res.data,
      'dictLabel',
      'dictValue',
    );
  });
};
init();

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '设备型号',
    dataIndex: 'model',
  },
  {
    title: '型号版本',
    dataIndex: 'version',
    hideInSearch: true,
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    valueEnum: { ...sysDeviceModeEnum.value },
  },
  {
    title: '型号描述',
    dataIndex: 'desc',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 80,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '设备型号',
    type: 'input',
    field: 'model',
    rules: [
      {
        required: true,
        message: '请输入设备型号',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请输入设备型号',
    },
  },
  {
    label: '型号版本',
    type: 'input',
    field: 'version',
    rules: [
      {
        required: true,
        message: '请输入型号版本',
        trigger: 'blur',
      },
      {
        message: '请输入正确的格式',
        pattern: /^[0-9a-zA-Z.]+$/,
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请输入型号版本',
    },
  },
  {
    label: '设备类型',
    type: 'select',
    field: 'type',
    rules: [
      {
        required: true,
        message: '请选择设备类型',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请选择设备类型',
      options: sysDeviceModeOption.value,
    },
  },
  {
    label: '型号描述',
    type: 'input',
    field: 'desc',
    props: {
      placeholder: '请输入型号描述',
    },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
  formProps: { labelCol: { span: 3 } },
});
const onAdd = () => {
  open({
    title: '新增',
    defaultValue: {},
    serviceApi: async (params: any): Promise<any> => {
      await addInfo(params);
      tableRef.value.refresh();
    },
  });
};
const onView = (record: any) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: { ...record },
    serviceApi: async (params: any): Promise<any> => {
      await updateInfo(params);
      tableRef.value.refresh();
    },
    hasEditPermission: hasPermission('deviceMode:edit'),
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onDelete = async () => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `是否确认删除当前设备型号？`,
    onOk: async () => {
      await delInfo(selectedRowKeys.value.join());
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};
</script>
